#include <Exceptions/Exception.h>
#include <Exceptions/OpenGLException.h>
#include <RenderSubSystem/RenderSubSystem.h>
#include <RenderSubSystem/cvRenderingDevice.h>

bool debug_check_glerrors(std::string msg)
{
	ILogger * logger;
	GLenum err = glGetError();
	if(err != GL_NO_ERROR)
	{
		logger = SubSystemManager::getInstance()->getSubSystemByName(RenderSubSystem::SUBSYSTEMNAME)->getLogger();
		msg += " FAILED with error code(s): ";
		do
		{
			switch(err)
			{
				case GL_INVALID_ENUM:		msg += "GL_INVALID_ENUM "; break;
				case GL_INVALID_VALUE:		msg += "GL_INVALID_VALUE "; break;
				case GL_INVALID_OPERATION:	msg += "GL_INVALID_OPERATION "; break;
				case GL_STACK_OVERFLOW:		msg += "GL_STACK_OVERFLOW "; break;
				case GL_STACK_UNDERFLOW:	msg += "GL_STACK_UNDERFLOW "; break;
				case GL_OUT_OF_MEMORY:		msg += "GL_OUT_OF_MEMORY "; break;
				case GL_TABLE_TOO_LARGE:	msg += "GL_TABLE_TOO_LARGE "; break;
				default:					msg += "UNKNOWN ERROR CODE "; break;
			}
			err = glGetError();
		} while(err != GL_NO_ERROR);

		logger->error(msg);
		return true;
	}
	return false;
}

void critical_check_glerrors(std::string msg)
{
	if(debug_check_glerrors(msg))
	{
		throw new Exception("LAST ERROR WAS CRITICAL.");
	}
}
